# -*- coding: utf-8 -*-
"""
报告生成模块
负责生成HTML格式的错误分析报告
"""

import os
from datetime import datetime
from typing import List, Dict
from jinja2 import Template
from .error_analyzer import ErrorInfo


class ReportGenerator:
    """HTML报告生成器"""
    
    def __init__(self, template_path="src/report_template.html"):
        """初始化报告生成器"""
        self.template_path = template_path
        self.html_template = self._get_html_template()
    
    def generate_report(self, errors: List[ErrorInfo], log_file_path: str, 
                       error_summary: Dict[str, int], monkey_finished: bool = False) -> str:
        """
        生成HTML报告
        
        Args:
            errors (List[ErrorInfo]): 错误信息列表
            log_file_path (str): 原始日志文件路径
            error_summary (Dict[str, int]): 错误统计摘要
            monkey_finished (bool): Monkey测试是否成功完成
            
        Returns:
            str: 生成的报告文件路径
        """
        # 报告应该生成在 reports 目录下
        project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
        reports_dir = os.path.join(project_root, 'reports')
        if not os.path.exists(reports_dir):
            os.makedirs(reports_dir)

        # 生成报告文件名
        log_filename = os.path.basename(log_file_path)
        log_name_without_ext = os.path.splitext(log_filename)[0]
        report_filename = f"{log_name_without_ext}_report.html"
        report_path = os.path.join(reports_dir, report_filename)
        
        # 准备模板数据
        template_data = {
            'log_filename': log_filename,
            'analysis_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'total_errors': len(errors),
            'error_summary': error_summary,
            'errors': errors,
            'monkey_finished': monkey_finished
        }
        
        # 渲染HTML模板
        template = Template(self.html_template)
        html_content = template.render(**template_data)
        
        # 写入报告文件
        try:
            with open(report_path, 'w', encoding='utf-8') as f:
                f.write(html_content)
            return report_path
        except Exception as e:
            print(f"生成报告时发生错误：{e}")
            return ""
    
    def _get_html_template(self) -> str:
        """
        获取HTML模板
        
        Returns:
            str: HTML模板字符串
        """
        try:
            project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
            template_full_path = os.path.join(project_root, self.template_path)
            with open(template_full_path, 'r', encoding='utf-8') as f:
                return f.read()
        except FileNotFoundError:
            print(f"错误：找不到模板文件 {self.template_path}")
            return ""